package com.fanghuaiming.seata.account.config;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2020/11/28 下午8:44
 *
 */
@Configuration
@MapperScan(basePackages = DataSourceProxyConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactoryBean")
public class DataSourceProxyConfig {

    static final String PACKAGE = "com.fanghuaiming.seata.account.dao.mapper";

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.seata.account")
    public DataSource dataSource() {
        return new HikariDataSource();
    }

    @Bean
    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSourceProxy);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mappers/*.xml"));
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }

}
